<template>
  <div class="roles">
    <!-- <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb> -->
    <Breadcrumb />

    <el-card class="box-card">
      <el-row>
        <el-col>
          <el-button type="primary" @click="dialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>

      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
              class="powers"
              :class="['bdbm', i1 === 0 ? 'bdtop' : '', 'center']"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="closeqx(scope.row, item1.id)">{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop', 'center']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag type="success" closable @close="closeqx(scope.row, item2.id)">{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="(item3, i3) in item2.children"
                      :key="item3.id"
                      closable
                      @close="closeqx(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>{{scope.row}} </pre> -->
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="400">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showeditUser(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUser(scope.row.id)"
              >删除</el-button
            >
            <el-button type="warning" icon="el-icon-setting"
             size="mini" @click="getRight(scope.row)">
              分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色 -->
    <el-dialog
      title="添加角色"
      @close="reset"
      :visible.sync="dialogVisible"
      width="40%"
    >
      <el-form
        :model="Roles"
        :rules="editFormRules"
        label-width="80px"
        ref="addRolesRef"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="Roles.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="Roles.roleDesc"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改角色 -->
    <el-dialog
      title="修改角色"
      @close="resetEdit"
      :visible.sync="editShow"
      width="40%"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        label-width="80px"
        ref="editFormRef"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editShow = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>


    <el-dialog
    title="分配权限"
    :visible.sync="showSetRight"
    @close="closeDef"
    width="50%">
        <el-tree   :data="rightsList"    :props="defaultProps" 
        show-checkbox     node-key="id"         default-expand-all
        :default-checked-keys="defkeys"  ref="treeRef">
        </el-tree>

        <span slot="footer" class="dialog-footer">
            <el-button @click="showSetRight = false">取 消</el-button>
            <el-button type="primary" @click="allotRights">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
import Breadcrumb from "../breadcrumb.vue";
export default {
  created() {
    this.getRoles();
  },
  components:{
    Breadcrumb
  },
  data() {
    return {
      rolesList: [],
      editShow: false,
      editForm: {},
      editFormRules: {
        roleName: [
          { required: true, message: "请输入角色名", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
        ],
      },
      dialogVisible: false,
      Roles: {
        roleName: "",
        roleDesc: "",
      },
      showSetRight:false,
      rightsList:[],
      defaultProps: {
          children: 'children',
          label: 'authName'
        },

        // 默认选中的节点ID值数组
      defkeys:[],
      // 当前即将分配权限的id
      roleId:'',
    };
  },
  methods: {
    async getRoles() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) return this.$message.error("获取数据失败！");
      this.rolesList = res.data;
      //   console.log(res);
    },
    async deleteUser(id) {
      const confirms = await this.$confirm(
        "此操作将永久删除该信息, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      if (confirms !== "confirm") {
        return this.$message.info("已取消删除");
      }
      const { data: res } = await this.$http.delete("roles/" + id);
      if (res.meta.status !== 200) return this.$message.error("删除信息失败！");
      this.$message.success("删除成功！");
      this.getRoles();
    },
    reset() {
      this.$refs.addRolesRef.resetFields();
    },
    resetEdit() {
      this.$refs.editFormRef.resetFields();
    },
    async showeditUser(id) {
      this.editShow = true;
      const { data: res } = await this.$http.get("roles/" + id);
      if (res.meta.status !== 200)
        return this.$message.error("获取用户信息失败");
      this.editForm = res.data;
    },
    async editUser() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          "roles/" + this.editForm.roleId,
          {
            roleName: this.editForm.roleName,
            roleDesc: this.editForm.roleDesc,
          }
        );
        if (res.meta.status !== 200) return this.$message.error("编辑用户失败");
        this.$message.success("编辑用户成功");
        this.editShow = false;
        this.getRoles();
      });
    },
    addRoles() {
      this.$refs.addRolesRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post("roles", this.Roles);
        if (res.meta.status !== 201) return this.$message.error("添加角色失败");
        this.$message.success("添加角色成功");
        this.dialogVisible = false;
        this.getRoles();
      });
    },
    async closeqx(role,powerId) {
      const confirms = await this.$confirm(
        "此操作将永久删除该信息, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      if (confirms !== "confirm") {
        return this.$message.info("已取消删除");
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${powerId}`
      );
      if (res.meta.status !== 200) return this.$message.error("删除权限失败！");
      this.$message.success("删除成功！");
    //   this.getRoles()
    role.children = res.data
    },
    closeDef(){
      this.defkeys = []
    },
    async getRight(role){
        this.roleId = role.id
        const {data:res} = await this.$http.get('rights/tree')
        if (res.meta.status !== 200) return this.$message.error("获取权限失败！");

        this.rightsList = res.data

        this.getdefKeys(role, this.defkeys)
        this.showSetRight = true
    },
    // 通过递归的形式获取角色下所有的三级权限id,保存到数组中
    getdefKeys(node, arr){
        // 如果当前node节点下不包含children就是三级节点，就push到arr数组中
        if(!node.children){
            return arr.push(node.id)
        }
        node.children.forEach( item => this.getdefKeys(item, arr) );
    },
    async allotRights(){
        const keys = [...this.$refs.treeRef.getCheckedKeys(),
            ...this.$refs.treeRef.getHalfCheckedKeys()   ]
        const idStr = keys.join(',')
        const {data:res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr})
        if(res.meta.status !== 200) return this.$message.error('分配权限失败')
        this.$message.success('分配成功!')
        this.getRoles()
        this.showSetRight = false
    },
  },
};
</script>

<style lang="scss" scoped>
.roles {
  .el-card {
    margin: 30px 0;
    .powers {
      padding: 0 40px;
      .el-tag {
        margin: 6px;
      }
    }
  }
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbm {
  border-bottom: 1px solid #eee;
}
.center {
  display: flex;
  align-items: center;
}
</style>